package net.khoroshev.dveri;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

public class MVCInterceptor implements HandlerInterceptor{

	Logger log = Logger.getLogger(MVCInterceptor.class.getName());
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		log.finest(">>preHandle()");
		log.finest("<<preHandle()");
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.finest(">>postHandle()");
		String theme = (String) request.getSession().getAttribute("theme");
		if (theme != null) {
			modelAndView.getModel().put("theme", theme);
		} else {
			modelAndView.getModel().put("theme", "style");
		}
		List<String> themes = new ArrayList<String>();
		String cssDirName = WebUtils.getRealPath(request.getSession().getServletContext(), "/css/");
		if (cssDirName != null) {
			File cssDir = new File(cssDirName);
			if (cssDir.isDirectory() && cssDir.canRead()) {
				File[] files = cssDir.listFiles();
				for (File file : files) {
					String fileName = file.getName();
					if (fileName.endsWith(".css")) {
						themes.add(fileName.substring(0, fileName.length()-4));
					}
				}
			}
		}
		modelAndView.addObject("themes", themes);
		log.finest("<<postHandle()");
		
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.finest(">>afterCompletion()");
		log.finest("<<afterCompletion()");
	}

}
